<?php

class AdminController extends Controller
{
	public $layout='/layouts/main';
	
	public $navText = '';

	public function init() {
	}
	
	public function getCacheId($type, $id) {
		return strtr(Yii::app()->params['bookCacheId'][$type], array('{id}'=>$id));
	}
	
	/**
	 * 获得章节评论
	 * @param int $bookId     书id
	 * @param int $chapterId  章节id
	 */
	public function getCommentsCounts($bookId, $chapterId) {
		$commentCounts = Yii::app()->db->createCommand()->from('{{module_'. $bookId .'_sections}}')
		->select('sectionId, commentsCounts')
		->where('chapterId=? and commentsCounts<>0', array($chapterId))
		->queryAll(false);
	
		return $commentCounts;
	}
	
	/**
	 * 获得章节信息
	 * @param string $flag
	 * @param string $chapter
	 */
	public function getChapterInfo($bookFlag, $chapterFlag) {
		$book = $this->getBookInfo($bookFlag);
		$cacheKey = $this->getCacheId('chapter', $bookFlag.$chapterFlag);
		$chapter = Yii::app()->cache->get($cacheKey);
		if ($chapter===false) {
			$chapter = Yii::app()->db->createCommand()
			->from('{{module_'. $book->moduleId .'_chapters}}')
			->where('url=?', array($chapterFlag))
			->queryRow();
			if ($chapter===false) $this->redirect(array('default/index','bookFlag'=>$bookFlag));
			Yii::app()->cache->set($cacheKey, $chapter, 86000);
		}
		return $chapter;
	}
	
	
	/**
	 * 获得书的信息
	 * @param string $flag 书名标识
	 */
	public function getBookInfo($bookFlag) {
		$cacheKey = $this->getCacheId('book', $bookFlag);
		$book = Yii::app()->cache->get($cacheKey);
		if ($book===false) {
			$book = Modules::model()->findByAttributes(array('nameFlag'=>$bookFlag));
			if (is_null($book)) $this->redirect('/');
			Yii::app()->cache->set($cacheKey, $book, 86000);
		}
		return $book;
	}
	
	/**
	 * 获得书的目录
	 * @param int $bookId  书的id
	 */
	public function getBookTableOfContents($bookId) {
		$cacheKey = $this->getCacheId('tableOfContents', $bookId);
		$tableOfContents = Yii::app()->cache->get($cacheKey);
		if ($tableOfContents===false) {
			$tableOfContents = Yii::app()->db->createCommand()
			->from('{{module_'. $bookId .'_chapters}}')
			->order('chapterSort DESC')->queryAll();
			Yii::app()->cache->set($cacheKey, $tableOfContents, 86000);
		}
		return $tableOfContents;
	}
	
	/**
	 * 获得段落列表
	 * @param int $bookId  书id
	 * @param int $chapterId 章id
	 */
	public function getSectionList($bookId, $chapterId) {
		$cacheKey = $this->getCacheId('section', $bookId.'_'.$chapterId);
		$sections = Yii::app()->cache->get($cacheKey);
		if ($sections==false) {
			$sections = Yii::app()->db->createCommand()->from('{{module_'. $bookId .'_sections}} s')
			->where('chapterId=?', array($chapterId))
			->order('s.sectionSort desc')
			->join('{{module_'. $bookId .'_translates}} t', 's.translateId=t.translateId')
			->queryAll();
	
			Yii::app()->cache->set($cacheKey, $sections, 86000);
		}
		return $sections;
	}
	
	public function getSectionInfo($bookFlag, $chapterFlag, $sectionId)
	{
		$book = $this->getBookInfo($bookFlag);
		$bookId = $book->moduleId;
		$section = Yii::app()->db->createCommand()->from('{{module_'. $bookId .'_sections}} s')
										->where('s.sectionId=?', array($sectionId))
										->join('{{module_'. $bookId .'_translates}} t', 's.translateId=t.translateId')
										->queryRow();							
		return $section;
	}

	public function getTranslateInfo($bookFlag, $chapterFlag, $translateId)
	{
		$book = $this->getBookInfo($bookFlag);
		$bookId = $book->moduleId;
		$section = Yii::app()->db->createCommand()->from('{{module_'. $bookId .'_translates}} t')
								->where('t.translateId=?', array($translateId))
								->join('{{module_'. $bookId .'_sections}} s', 's.sectionId=t.sectionId')
								->queryRow();
		
		return $section;
	}
	
	/**
	 * 创建导航
	 * @param string $bookFlag 书标识
	 * @param array $chapter  章节信息
	 */
	public function createNav($bookFlag, $chapter) {
		$prefixUrl = $this->createUrl('default/chapter', array('bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['nextUrl']));
		if ($chapter['isFirst']==1) {
			$this->nav = CHtml::link('目录', $this->createUrl('default/index', array('bookFlag'=>$bookFlag)));
			$this->nav .= ' &loz; '. CHtml::link('下一章 &raquo;', $this->createUrl('default/chapter', array('bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['nextUrl'])));
		}
		else if ($chapter['isFirst']==1) {
			$this->nav = CHtml::link('&laquo; 上一章', $this->createUrl('default/chapter', array('bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['prevUrl']))) .' &loz; ';
			$this->nav .= CHtml::link('目录', $this->createUrl('default/index', array('bookFlag'=>$bookFlag)));
		}
		else if ($chapter['isEnd']==0 && $chapter['isFirst']==0) {
			$this->nav = CHtml::link('&laquo; 上一章', $this->createUrl('default/chapter', array('bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['prevUrl']))) .' &loz; ';
			$this->nav .= CHtml::link('目录', $this->createUrl('default/index', array('bookFlag'=>$bookFlag)));
			$this->nav .= ' &loz; '. CHtml::link('下一章 &raquo;', $this->createUrl('default/chapter', array('bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['nextUrl'])));
		}
	}
	
	
	/**
	 * 创建快速导航
	 * @param int $bookId
	 * @param int $chapterId
	 */
	public function createExpressNavContent($bookId, $chapterId) {
	
		$cacheKey = $this->getCacheId('expressNav', $bookId.'-'.$chapterId);
	
		$expressNavContent = Yii::app()->cache->get($cacheKey);
		if ($expressNavContent==false) {
			$expressNavContent  = $this->getChapterNavByParentTitleId($bookId, $chapterId);
			Yii::app()->cache->set($cacheKey, $expressNavContent, 86000);
		}
	
		return $expressNavContent;
	}
	
	public function clearExpressNavCache($bookFlag, $chapterFlag)
	{
		$book = $this->getBookInfo($bookFlag);
		$bookId = $book->moduleId;
		$chapter = $this->getChapterInfo($bookFlag, $chapterFlag);
		$chapterId = $chapter['chapterId'];
		Yii::app()->cache->delete($this->getCacheId('expressNav', $bookId.'-'.$chapterId));
	}
	
	/**
	 * 获得父级标题
	 * @param unknown_type $chapter_id
	 * @param unknown_type $title_parent
	 * @return string
	 */
	public function getChapterNavByParentTitleId($bookId, $chapterId, $titleParent=0) {
		static $_i = 0;
		$text = "";
		if ($_i==0) {
			$sql = "
			SELECT * FROM {{module_{$bookId}_sections}} s, {{module_{$bookId}_translates}} t
			WHERE s.chapterId={$chapterId} AND s.sectionType=". SectionHelper::SECTION_TYPE_TITLE ."
			AND s.titleParent={$titleParent} AND
			s.translateId = t.translateId
			ORDER BY s.sectionSort DESC
			";
		}
		else {
			$sql = "
			SELECT * FROM {{module_{$bookId}_sections}} s, {{module_{$bookId}_translates}} t
			WHERE s.chapterId={$chapterId} AND s.titleParent={$titleParent} AND
			s.translateId = t.translateId
			ORDER BY s.sectionSort DESC
			";
		}
		$datas = Yii::app()->db->createCommand($sql)->queryAll();
		if (count($datas)>0) $text="<ul style=\"list-style-type:auto;\">";
		foreach($datas as $data) {
			$text.="<li><a href=\"#cn".$data['sectionId']."\" onClick=\"toggleChapternav()\" style=\"color:#599ACB;\">". $data['sectionText'] ."</a>".$this->getChapterNavByParentTitleId($bookId, $chapterId, $data['sectionId'])."</li>";
		}
	
		if (count($datas)>0) $text.="</ul>";
		$_i++;
		return $text;
	}
	
	/**
		* 获得评论列表
		* @param string $bookFlag
		* @param string $chapterFlag
		*/
		public function getComments($bookFlag, $chapterFlag) {
		$cacheKey = $this->getCacheId('comments', $bookFlag);
		$commentsString = Yii::app()->cache->get($cacheKey);
	
		if ($commentsString===false) {
		$book = $this->getBookInfo($bookFlag);
		$bookId = $book->moduleId;
		$chapter = $this->getChapterInfo($bookFlag, $chapterFlag);
		$chapterId = $chapter['chapterId'];
	
		$comments = Yii::app()->db->createCommand()->from('{{module_'.$bookId.'_comments}}')
		->order('addTime desc')
		->queryAll();
	
		$commentsString = '';
		foreach( $comments as $comment) {
		if (trim($comment['website'])=='') {
		$link = CHtml::encode($comment['name']);
		}
		else {
		$link = CHtml::link(CHtml::encode($comment['name']), $comment['website']);
		}
		$date = CHtml::tag('span', array('class'=>'meta'), date("Y-m-d H:i:s", $comment['addTime']));
		$content = "<dd>". CHtml::tag('p', array(), CHtml::encode($comment['comment'])) ."</dd>";
				$li_content = "<dl><dt>".$link.' '.$date."</dt>". $content."</dl>";
				$commentsString .= CHtml::tag('li',array('class'=>'comment', 'id'=> $comment['commentId']), $li_content)."\n";
		}
	
		Yii::app()->cache->set($cacheKey, $commentsString, 86000);
	}
		echo $commentsString;
	}
	
	public function saveComments($bookFlag, $chapterFlag) {
		$_errors = array();
			$comment = Yii::app()->request->getPost('comment');
	
					if ('' == trim($comment)) $_errors[]='comment';
	
					$email = Yii::app()->request->getPost('email');
					if ('' == trim($email)) $_errors[]='email';
	
					$name = Yii::app()->request->getPost('name');
					if ('' == trim($name)) $_errors[]='name';
	
					$nodenum = Yii::app()->request->getPost('nodenum');
					$url = Yii::app()->request->getPost('url');
	
					if (count($_errors)>0) {
					echo CJSON::encode($_errors);
					exit;
		}
	
		$book = $this->getBookInfo($bookFlag);
		$bookId = $book->moduleId;
		$chapter = $this->getChapterInfo($bookFlag, $chapterFlag);
		$chapterId = $chapter['chapterId'];
	
		$params = array(
				'comment'=>$comment,
				'email'=>$email,
				'name'=>$name,
				'website'=>$url,
				'sectionId'=>$nodenum,
				'clientIp'=>AppHelper::getClientIp(),
				'addTime'=>time(),
				'chapterId'=>$chapterId
				);
				$sql = "
				INSERT INTO {{module_".$bookId."_comments}} (
				name, email, website, comment, clientIp, addTime, sectionId, chapterId
				) VALUES (:name, :email, :website, :comment, :clientIp, :addTime, :sectionId, :chapterId)
				";
				if (Yii::app()->db->createCommand($sql)->execute($params)!=false) {
						$commentId = Yii::app()->db->getLastInsertID();
						$link = CHtml::link($name, $url);
						$date = CHtml::tag('span', array('class'=>'meta'), date("Y-m-d H:i:s", $params['addTime']));
						$content = "<dd>". CHtml::tag('p', array(), $comment) ."</dd>";
		$li_content = "<dl><dt>".$link.$date."</dt>".$content."</dl>";
		echo CHtml::tag('li',array('class'=>'comment', 'id'=> $commentId, $li_content));
	
				//更新段落评论数
				Yii::app()->db->createCommand()->update('{{module_'.$bookId.'_sections}}',
						array('commentsCounts'=>new CDbExpression('commentsCounts+1')),
						'sectionId='.$nodenum
						);
	
								//清除本章评论数据缓存
								Yii::app()->cache->delete($this->getCacheId('commentsCounts', $bookFlag.'_'.$chapterFlag));
								//清除显示评论
	Yii::app()->cache->delete($this->getCacheId('sectionComments', $bookFlag.'-'.$chapterFlag.'-'.$nodenum));
	//清除所有评论
	Yii::app()->cache->delete($this->getCacheId('comments', $bookFlag));
	}
	}
	
	
	public function getChapterFlag($bookId, $chapterId)
	{
		$chapterFlag = Yii::app()->db->createCommand()->from('{{module_'.$bookId.'_chapters}}')
								->where('chapterId=?', array($chapterId))
								->select('url')->queryScalar();
		return $chapterFlag;
	}
}
